package com.bdpn.ch05.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

public class AuthorizationFilter implements Filter {

    @Override
    public void init(jakarta.servlet.FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest HttpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletRequest;

        if (HttpRequest.getSession().getAttribute("loginUser") == null) {
            httpServletResponse.setContentType("text/html;charset=utf-8");
            PrintWriter out = httpServletResponse.getWriter();
            out.println("<script>alert('请先进行登入，在进行后续操作！（Filter控制）');location.href='"+HttpRequest.getContextPath()+"/login.html';</script>");
        }else {
            filterChain.doFilter(HttpRequest, httpServletResponse);
        }
    }

    @Override
    public void destroy() {
    }
}
